int trap(int* height, int heightSize) {
    int i = 0, left = -1, right = -1;
    int sum = 0;

    while(right == -1 && i < heightSize)
    {
        if((i == 0 || height[i] > height[i - 1]) && (i == heightSize - 1 || height[i] > height[i + 1]))
        right = i;
        i++;
    }

    while(i < heightSize)
    {
        while(left == -1 && i < heightSize)
        {
            if((i == 0 || height[i] > height[i - 1]) && (i == heightSize - 1 || height[i] > height[i + 1]))
            {
                left = right;
                right = i;
            }
            i++;
        }
        
        if(left == -1 || right == -1)
        break;

        int maxHeight = height[left] < height[right] ? height[left] : height[right];
        for(int j = left + 1; j < right; j++)
        sum += maxHeight - height[j];

        left = -1;
    }
    return sum;
}